import React, { Fragment, useEffect } from 'react'
import { Card, Button, Table, Modal, Form, Input, message, Select, Tag, InputRef } from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons'
import { ColumnsType } from 'antd/lib/table';
import { useState, useRef } from 'react';
import attrApi, { AttrListData, AttrData, CategoryListData, AttrValueData, AttrValueListData } from '@/api/product/attr'
import '../trademark/index.less'

export default function Attr() {

    const { Option } = Select;
    const [showStatus, setShowStatus] = useState(0)
    
    const columns: ColumnsType<AttrData> = [
        {
            title: '序号',
            render: (row, record, index) => index + 1,
            width: 80,
            align: 'center'
        },
        {
            title: '属性名称',
            dataIndex: 'attrName',
            width: 150
        },
        {
            title: '属性名称列表',
            dataIndex: 'attrValueList',
            render: row => {
                return (
                    <>
                        {row.map((attrValue: AttrValueData) => {
                            return <Tag key={attrValue.id} color="#108ee9" >{attrValue.valueName}</Tag>
                        })}
                    </>
                )
            }
        },
        {
            title: '操作',
            render: (row) => {
                return (
                    <>
                        <Button
                            size='small'
                            icon={<EditOutlined />}
                            style={{ backgroundColor: '#E6A23C', color: '#fff', marginRight: '10px' }}
                            onClick={() => {addOrUpdateAttrInit(row)}}
                        ></Button>

                        <Button
                            size='small'
                            icon={<DeleteOutlined />}
                            style={{ backgroundColor: '#F56C6C', color: '#fff', marginRight: '10px' }}
                            onClick={() => {deleteAttr(row)}}
                        ></Button>

                    </>
                )
            }
        }
    ]

    
    const attrValueColumns: ColumnsType<AttrValueData> = [
        {
            title: '序号',
            render: (row, record, index) => index + 1,
            width: 80,
            align: 'center'
        },
        {
            title: '属性值名称',
            render: (row, record, index) => {
                // input 记得要用 defaultValue , 如果直接使用 value 就会绑死
                return (
                    <>
                        <Input
                            onChange={e => changeAttrValue(e, index)}
                            onBlur={() => addAttrValue(row, index)}
                            onFocus={() => setCurrentIndex(index)}
                            defaultValue={row.valueName}
                            style={{ display: currentIndex === index ? '' : 'none' }}
                            autoFocus
                        ></Input>

                        <span
                            onClick={() => setCurrentIndex(index)}
                            style={{ display: currentIndex === index ? 'none' : '' }}
                        >{row.valueName}</span>
                    </>
                )
            }
        },
        {
            title: '操作',
            render: (row, record, index) => <Button onClick={() => removeAttrValue(index)} size='small' icon={<DeleteOutlined />} style={{ backgroundColor: '#F56C6C', color: '#fff'}} ></Button>
        }
    ]


    const [category1List, setCategory1List] = useState<CategoryListData>([])
    const [category2List, setCategory2List] = useState<CategoryListData>([])
    const [category3List, setCategory3List] = useState<CategoryListData>([])
    const [category1Id, setCategory1Id] = useState('')
    const [category2Id, setCategory2Id] = useState('')
    const [category3Id, setCategory3Id] = useState('')
    const [form] = Form.useForm()
    const [addForm] = Form.useForm()
    // const inputEl = useRef<InputRef>(null)
    const [attrList, setAttrList] = useState<AttrListData>([])


    const [attrName, setAttrName] = useState('')
    
    const [attrDetail, setAttrDetail] = useState<AttrData>({
        attrName: '',
        categoryId: category3Id,
        categoryLevel: 3,
        attrValueList: []
    })

    const [attrValueList, setAttrValueList] = useState<AttrValueListData>([])
    let arr = [...attrValueList]

    
    useEffect(() => {
        getCategory1List()
    }, [])


    useEffect(() => {
        if (category1Id) getCategory2List()
    }, [category1Id])


    useEffect(() => {
        if (category2Id) getCategory3List()
    }, [category2Id])


    useEffect(() => {
        if (category3Id) getAttrList()
    }, [category3Id])



    const getCategory1List = async () => {
        try {
            const result = await attrApi.getCategory1List()
            setCategory1List(result)
        } catch (error) {
            message.error('获取一级分类列表失败')
        }
    }

    const getCategory2List = async () => {
        try {
            const result = await attrApi.getCategory2List(category1Id)
            setCategory2List(result)
        } catch (error) {
            message.error('获取二级分类列表失败')
        }
    }

    const getCategory3List = async () => {
        try {
            const result = await attrApi.getCategory3List(category2Id)
            setCategory3List(result)
        } catch (error) {
            message.error('获取三级分类列表失败')
        }
    }

    const getAttrList = async () => {
        try {
            const result = await attrApi.getAttrList(category1Id, category2Id, category3Id)
            setAttrList(result)
        } catch (error) {
            message.error('获取属性列表失败')
        }
    }

    const handleCategory1 = (val: string) => {
        setCategory2List([])
        setCategory3List([])
        setCategory1Id(val)
        setCategory2Id('')
        setCategory3Id('')
        setAttrList([])
        form.resetFields(['c2', 'c3'])
        // setState() 有时是异步的!!!
        // setState() 只在合成事件和钩子函数中是“异步”的,在原生事件和setTimeout中都是同步的
        // 可以在 useEffect 中发请求
        // getCategory2List()
    }

    const handleCategory2 = (val: string) => {
        setCategory3List([])
        setCategory2Id(val)
        setCategory3Id('')
        setAttrList([])
        form.resetFields(['c3'])
        // getCategory3List()
    }


    // 判断新增还是更新
    const addOrUpdateAttrInit = (row: any) => {
        setShowStatus(1)

        if (!row.id) {
            setAttrDetail(
                {
                    attrName: '',
                    categoryId: category3Id,
                    categoryLevel: 3,
                    attrValueList: []
                }
            )
            setAttrValueList([])
            setAttrName('')
            addForm.setFieldsValue({attrName: ''})
        } else {
            setAttrDetail(row)
            setAttrValueList(row.attrValueList)
            // 需要存 attrName
            setAttrName(row.attrName)
            // 表单内容必须通过表单api来更改
            addForm.setFieldsValue({attrName: row.attrName})
        }
    }


    // Form 子控件值更改时触发, 修改的值, 全部值
    // Form.Item 必须要有 name
    // 添加属性
    const saveAttrName = (val: any, allVal: any) => {
        if (val.attrName && val.attrName.trim()) setAttrName(val.attrName)
        else {
            setAttrName('')
            message.error('属性名不能为空')
        }
    }

    // 验证属性名
    const checkAttr = () => {
        attrList.forEach(item => {
            if (item.attrName === attrName) {
                message.error('该属性名已存在')
                setAttrName('')
                addForm.setFieldsValue({attrName: ''})
                return
            }
        })
    }


    // 当前正在编辑的 input, currentIndex === index 为 input, 否则为 span
    let [currentIndex, setCurrentIndex] = useState(-1)

    // 添加属性对应的属性值
    const showAddAttrValueInput = () => {
        setCurrentIndex(attrValueList.length)
        setAttrValueList([...attrValueList, { valueName: '' }])
    }

    // input onChange
    const changeAttrValue = (e: any, index: number) => {
        arr[index].valueName = e.target.value
        setAttrValueList(arr)
    }


    // input 失焦
    const addAttrValue = (row: any, index: number) => {
        setCurrentIndex(-1)
        if (!row.valueName || !row.valueName.trim()) {
            arr.splice(index, 1)
            setAttrValueList(arr)
        }
        else {
            attrValueList.forEach(item => {
                if (item !== row && item.valueName === row.valueName ) {
                    message.error('属性名不能重复')
                    arr.splice(index, 1)
                    setAttrValueList(arr)
                    return
                }
            })
        }
    }


    // 删除属性值, 最后统一发请求
    const removeAttrValue = (index: number) => {
        arr.splice(index, 1)
        setAttrValueList(arr)
    }


    // 保存
    const save = async () => {
        // 直接 setAttrDetail, 是异步的, 需要使用一个新的非state数据 saveParams 来更新, 这样是同步的
        // 整理好 saveParams 之后, 用 saveParams 发请求
        // 必须得重新赋值一次 categoryId, 初始化的时候是空的, 后续虽然通过 setCategory3Id 改了 3id
        // 但是 arttrDetail 中一开始获取的是 空串 3id, 必须得通过 setAttrDetail 来改
        let saveParams = attrDetail
        saveParams = {
            ...attrDetail,
            attrName,
            attrValueList,
            categoryId: category3Id
        }

        // console.log('saveParams', saveParams)

        if (!attrName) {
            message.error('属性名不能为空')
            return
        }

        if (!attrValueList.length) {
            message.error('至少需要一个属性值')
            return
        }

        try {
            await attrApi.saveAttr(saveParams)
            message.success('保存成功')
            setShowStatus(0)
            getAttrList()
        } catch (error) {
            message.error('保存失败')
        }
    }


    // 删除
    const deleteAttr = async (row: any) => {
        try {
            await attrApi.deleteAttr(row.id as string)
            message.success('删除成功')
            getAttrList()
        } catch (error) {
            message.error('删除失败')
        }
    }


    return (
        <>
            <Card >
                <Form layout='inline' form={form} >

                    <Form.Item label='一级分类' name='c1'>
                        <Select onChange={handleCategory1} style={{ width: 200, marginRight: 20 }} placeholder='请选择' >
                            {category1List.map(c1 => {
                                return <Option key={c1.id} value={c1.id}>{c1.name}</Option>
                            })}
                        </Select>
                    </Form.Item>

                    <Form.Item label='二级分类' name='c2'>
                        <Select onChange={handleCategory2} style={{ width: 200, marginRight: 20 }} placeholder='请选择' >
                            {category2List.map(c2 => {
                                return <Option key={c2.id} value={c2.id} >{c2.name}</Option>
                            })}
                        </Select>
                    </Form.Item>

                    <Form.Item label='三级分类' name='c3'>
                        <Select onChange={val => setCategory3Id(val)} style={{ width: 200 }} placeholder='请选择' >
                            {category3List.map(c3 => {
                                return <Option key={c3.id} value={c3.id}>{c3.name}</Option>
                            })}
                        </Select>
                    </Form.Item>

                </Form>
            </Card>


            <>
                <div style={{display: showStatus === 0 ? 'block' : 'none' }}>
                    <Card>
                        <Button
                            onClick={addOrUpdateAttrInit}
                            type='primary'
                            icon={<PlusOutlined />}
                            disabled={!category3Id}
                        >
                        添加属性</Button>
                    </Card>

                    <Card>
                        <Table
                            dataSource={attrList}
                            columns={columns}
                            rowKey='id'
                            bordered
                            rowClassName='tableItem'
                        >

                        </Table>
                    </Card>

                </div>

                <Card style={{display: showStatus === 1 ? 'block' : 'none' }}>
                    <Form onValuesChange={saveAttrName} form={addForm} >
                        <Form.Item
                            initialValue={attrName}
                            name='attrName'
                            // valuePropName='attrName'
                            label='属性名'
                            style={{ fontWeight: 'bold' }}
                            wrapperCol={{ span: 4 }}
                        >
                            <Input placeholder='输入属性名' onBlur={checkAttr} ></Input>
                        </Form.Item>
                    </Form>

                    <Button
                        type='primary'
                        style={{ margin: '0 8px 16px 0' }}
                        onClick={showAddAttrValueInput}
                    >
                    添加属性值</Button>
                    <Button onClick={() => setShowStatus(0)}>取消</Button>

                    <Table
                        dataSource={attrValueList}
                        columns={attrValueColumns}
                        bordered
                        // 有问题, 输入的时候还没失焦确定, 两个相同的属性值就会报错
                        // 需要一个特殊的数据来标识
                        rowKey='valueName'
                    ></Table>

                    <Button type='primary' style={{margin: '16px 16px 0 0'}} onClick={save} >保存</Button>
                    <Button onClick={() => setShowStatus(0)}>取消</Button>
                </Card>
            </>
        </>
    )
}

